package cn.edu.tsinghua.training.cms.demo.action;

import java.util.Date;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import cn.edu.tsinghua.training.cms.demo.entity.Admin;
import cn.edu.tsinghua.training.cms.demo.entity.Article;
import cn.edu.tsinghua.training.cms.demo.entity.Channel;
import cn.edu.tsinghua.training.cms.demo.service.ArticleService;

@SuppressWarnings("serial")
@Results({
	@Result(name="list", location="channel_article_list", type="redirectAction"),
	@Result(name="article_list", location="/article/article_list.jsp", type="redirect"),
	@Result(name="article_search", location="/article/article_edit.jsp", type="redirect")
})
public class ArticleAction extends BaseAction {

	private Article article;
	@Autowired
	private ArticleService articleService;
	
	@Action("article_add")
	public String add() throws Exception {
		article.setAdmin((Admin) getSession().get("admin"));
		article.setChannel((Channel) getSession().get("channel")); 
		if (article.getTime() == null) {
			article.setTime(new Date());
		}
		articleService.add(article);
		return "list";
	}
	
	@Action("article_list")
	public String list() throws Exception {
		getSession().put("list", articleService.queryAll());
		return "article_list";
	}
	
	@Action("article_search")
	public String search() throws Exception {
		getSession().put("article", articleService.queryById(article.getId()));
		return "article_search";
	}
	
	@Action("article_update")
	public String update() throws Exception {
		article.setAdmin((Admin) getSession().get("admin"));
		article.setChannel((Channel) getSession().get("channel")); 
		articleService.update(article);
		return "list";
	}
	
	@Action("article_remove")
	public String remove() throws Exception {
		articleService.delete(article);
		return "list";
	}
	
//	setters and getters

	public void setArticle(Article article) {
		this.article = article;
	}
	
	public Article getArticle() {
		return article;
	}

}